package com.hundsun.yr.universal.p2p.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.hundsun.yr.universal.library.utils.HsNumberUtils;
import com.hundsun.mobile.zwgt.R;

/**
 * 
 * @author tonglj
 *
 */
public class AddSubView extends LinearLayout {
	private Context context;
	private OnNumChangeListener onNumChangeListener;
	/**
	 * +按钮
	 */
	private ImageButton addButton;
	/**
	 * -按钮
	 */
	private ImageButton subButton;
	/**
	 * 保存值
	 */
	private EditText editText;
	/**
	 *editText中的数值
	 */
	private double value; // editText中的数值
	/**
	 * 累加步长
	 */
	private Double step = 1d;
	private int type = INPUTTYPE_PERCENT;
	public final static int INPUTTYPE_PERCENT = 0x001;
	public final static int INPUTTYPE_INTEGER = 0x002;
	/**
	 * 最小值
	 */
	private Double MinValue = 0.0;
	/**
	 * 最大值
	 */
	private Double MaxValue = 100.0;
	/**
	 * 判断是手动输入的还是按键修改
	 */
	private boolean isBtnPass = false;
	
	private int selection = 0;
	

	public AddSubView(Context context) {
		this(context,null);
	}


	/**
	 * 从XML中实例化
	 */
	public AddSubView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		value = MinValue;
		if(attrs != null){
			//通过xml文件设置的数据
			TypedArray  a = context.obtainStyledAttributes(attrs, R.styleable.AddSubView);
			type =  a.getInt(R.styleable.AddSubView_numberType, INPUTTYPE_PERCENT);
			if(type == INPUTTYPE_PERCENT){
				MaxValue = (double) 100;
				step = 1d;
			}else{
				MaxValue = Double.MAX_VALUE;
				step = 100d;
			}
			MinValue = (double) a.getFloat(R.styleable.AddSubView_mindouble, MinValue.floatValue());
			value = (double) a.getFloat(R.styleable.AddSubView_defaultdouble, MinValue.floatValue());
			MaxValue = (double) a.getInt(R.styleable.AddSubView_maxinteger, MaxValue.intValue());
			step = (double) a.getFloat(R.styleable.AddSubView_step, step.floatValue());
		}
		init(attrs);
	}
	/**
	 * 设置最小值
	 * @param min
	 */
	public void setMinValue(double min){
		MinValue = min;
//		value = min;
		setText(value);
	}
	
	/**
	 * 设置最大值
	 * @param max
	 */
	public void setMaxValue(double max){
		MaxValue = max;
		setText(value);
	}

	/**
	 * 初始化
	 */
	private void init(AttributeSet attrs) {
		View.inflate(context, R.layout.view_addsub, this);
		editText = (EditText)findViewById(R.id.view_addsub_et);
		addButton = (ImageButton)findViewById(R.id.view_addbtn);
		subButton = (ImageButton)findViewById(R.id.view_subbtn);
		initialise(attrs); // 实例化内部view
		//获得焦点的时候选中
		editText.setSelectAllOnFocus(true);
		//无论怎么样没有光标
		editText.setCursorVisible(true);

		//规定了edidtext的规则
		editText.setFilters(new InputFilter[]{new InputFilter() {
			@Override
			public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
				try{
					if(type == INPUTTYPE_INTEGER){
						int value = Integer.parseInt(dest.toString()+source.toString());
						if(value > MaxValue){
							return "";
						}
					}
				}catch(Exception e){
				}
				
				return null; 
			}
		}});
		setViewListener();
	}


	/**
	 * 实例化内部View
	 */
	private void initialise(AttributeSet attrs) {
		
		if(type == INPUTTYPE_INTEGER){
			// 设置输入类型为数字
			editText.setInputType(android.text.InputType.TYPE_CLASS_NUMBER);
			String digits = "1234567890";
			//设置可以输入的字符集
			editText.setKeyListener(DigitsKeyListener.getInstance(digits)); 
		}else{
			String digits = "1234567890%。";
			editText.setInputType(android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL);
			editText.setKeyListener(DigitsKeyListener.getInstance(digits));
		}
		setText();
		subButton.setEnabled(false);
	}




	/**
	 * 设置editText中的值
	 * 
	 * @param num
	 */
	public void setNum(double num) {
		this.value = num;
		setText(value);
	}

	/**
	 * 获取editText中的值
	 * 
	 * @return
	 */
	public double getNum() {
		if (editText.getText().toString() != null) {
			return Double.parseDouble(editText.getText().toString().replace("%",""));
		} else {
			return MinValue;
		}
	}

	




	/**
	 * 设置输入框中的字体大小
	 * 
	 * @param spValue
	 *            字体大小SP
	 */
	public void setTextSize(int spValue) {
		editText.setTextSize(spValue);
	}

	



	/**
	 * 设置EditText文本变化监听
	 * 
	 * @param onNumChangeListener
	 */
	public void setOnNumChangeListener(OnNumChangeListener onNumChangeListener) {
		this.onNumChangeListener = onNumChangeListener;
	}

	/**
	 * 设置文本变化相关监听事件
	 */
	private void setViewListener() {
		addButton.setOnClickListener(new OnButtonClickListener());
		subButton.setOnClickListener(new OnButtonClickListener());
		editText.addTextChangedListener(new OnTextChangeListener());
		editText.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction()==MotionEvent.ACTION_DOWN){
					editText.setSelectAllOnFocus(true);
//					editText.invalidate();
					return false;
				}
				return true;
			}
		});
	}

	/**
	 * 加减按钮事件监听器
	 * 
	 */
	class OnButtonClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			isBtnPass = true;
			String numString = editText.getText().toString();
			if (numString == null || numString.equals("")) {
				value = (double) step;
			} else {
				int ID = v.getId();
				if (R.id.view_addbtn == ID) {//增加按钮点击事件
					value = value+step;
					if (value < step) // 先加，再判断
					{
						value = MinValue; 
					} else if(value >= MaxValue) {
						setSubEnable(true);
						setAddEnable(false);
						value = MaxValue;
					} else {
						setSubEnable(true);
						setAddEnable(true);
						if (onNumChangeListener != null) {
							onNumChangeListener.onNumChange(AddSubView.this, value);
						}
					}
				} else if (R.id.view_subbtn == ID) {
					value = value-step;
					if (value <= MinValue) // 先减，再判断
					{
						value = MinValue;
						setSubEnable(false);
						setAddEnable(true);
					} else {
						setSubEnable(true);
						setAddEnable(true);
						if (onNumChangeListener != null) {
							onNumChangeListener.onNumChange(AddSubView.this, value);
						}
					}
				}
			}
			setText();
		}
	}
	
	

	/**
	 * EditText输入变化事件监听器
	 * 
	 */
	class OnTextChangeListener implements TextWatcher {

		private boolean isRun = false;

		@Override
		public void afterTextChanged(Editable s) {
			if(isRun ){//每次录入只调用一次防止堆栈溢出
                isRun = false;
                return;
            }
            isRun = true;
			String numString = s.toString();
			if(type == INPUTTYPE_INTEGER){
				selection = numString.length();
			}else{
				if(numString.contains("%")){
					numString = numString.replace("%", "");
				}
//				value = (double) Double.parseDouble(numString);
				selection = numString.indexOf(".");
				if(selection == -1){
					selection = numString.length();
				}
			}
			try{
				value = (double) Double.parseDouble(numString);
				if(value<MinValue){
					value = MinValue;
				}
			}catch(Exception e){
				value = MinValue;
			}
//			if(value>MaxValue){
//				value = MaxValue;
//			}
//			editText.setSelection(s.length());
//			editText.invalidate();
			setText();
			
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if(count == 0){
				selection = 0;
			}
		}

	}
	/**
	 * 设置减号按钮可否点击
	 * @param flag
	 */
	private void setSubEnable(boolean flag){
		if(subButton.isEnabled()&&!flag){
			subButton.setEnabled(false);
			subButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_minus));
		}else if(!subButton.isEnabled()&&flag){
			subButton.setEnabled(true);
			subButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_minusing));
		}
		
	}
	
	/**
	 * 设置加号按钮可否点击
	 * @param flag
	 */
	private void setAddEnable(boolean flag){
		if(addButton.isEnabled()&&!flag){
			addButton.setEnabled(false);
			addButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_add));
		}else if(!addButton.isEnabled()&&flag){
			addButton.setEnabled(true);
			addButton.setImageDrawable(getResources().getDrawable(R.drawable.icon_adding));
		}
	}
	
	public double getValue(){
		return value;
	}
	public int getIntValue(){
		return ((int)value);
	}
	

	private void setText(){
		setText(value);
	}

	/**
	 * 设置EditText里面的值
	 * @param value
     */
	private void setText(Double value){
		// 如果最小值等于最大值，加减按钮都不可用
		if (MinValue.equals(MaxValue)) {
			value = MinValue;
			setSubEnable(false);
			setAddEnable(false);
		} else {
			// 判断是否临界最大和最小值之间，如果value的取值不符合规则就value的取值需要进行特殊的赋值
			if (value <= MinValue) {
				if (isBtnPass) {
					value = MinValue;
				}
				setSubEnable(false);
				setAddEnable(true);
			} else if (value >= MaxValue) {
				value = MaxValue;
				setSubEnable(true);
				setAddEnable(false);
			}
		}
		this.value = value.doubleValue();
		if(type == INPUTTYPE_INTEGER){
			editText.setText(String.valueOf(value.intValue()));
		}else if(type == INPUTTYPE_PERCENT){
//			//设置百分数精确度2即保留两位小数
		String	VALUE = HsNumberUtils.formartPercent(value/100,2);
		editText.setText(VALUE);
		}
		if(!isBtnPass){
			editText.setSelection(selection);
		}
		isBtnPass = false;
		if (onNumChangeListener != null) {
			onNumChangeListener.onNumChange(AddSubView.this, this.value);
		}
	}
	
	
	public void setUnEnable(){
		setSubEnable(false);
		setAddEnable(false);
		editText.setEnabled(false);
	}
	

	public interface OnNumChangeListener {
		/**
		 * 输入框中的数值改变事件
		 * 
		 * @param view
		 *            整个AddAndSubView
		 * @param num
		 *            输入框的数值
		 */
		public void onNumChange(View view, double num);
	}
	/**
	 * 设置步长
	 * @param step
	 */
	public void setStep(double step) {
		this.step = step;
		
	}


	public void setDefaultValue(double value) {
		this.value = value;
		setText();
	}

}
